import requests
import re

def getHTMLText(url):
    try: # try ...  except ... 意思是程序不会因为一些异常而退出
        r = requests.get(url, timeout = 30)
        print(r.status_code)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

def parsePage(ilt, html):
    try:
        plt = re.findall(r'\"view_price\":\"[\d\.]*\"',html)
        tlt = re.findall(r'\"raw_title\":\".*?\"', html)
        print(str(len(plt)))
        for i in range(len(plt)):
            price = eval(plt[i].split(':')[1])
            title = eval(tlt[i].split(':')[1])
            print(str(price))
            ilt.append([price, title])
    except:
        print("异常")

def printGoodsList(ilt):
    tplt = "{:4}\t{:8}\t{:16}"
    print(tplt.format("序号", "价格", "商品名称"))
    count = 0
    for g in ilt:
        count = count +1
        print(tplt.format(count, g[0], g[1]))

def jingdong(url):
    try:
        kv = {'user-agent':'Mozilla/5.0'}
        r = requests.get(url, headers=kv)
        print(r.url)
        print(r.status_code)
        r.raise_for_status()
        r.encoding = r.apprant_encoding
        print(r.text)
        return t.text
    except:
        return "异常"


def main():
    # goods = "游戏本"
    goods = "cpu"
    depth = 2
    # https://search.jd.com/Search?keyword=游戏本i7 爬不了淘宝，我爬京东
    start_url = "https://search.jd.com/Search?keyword=" + goods
    html = jingdong(start_url)
    print(html)


   # infolist = [] # 这个数据结构是什么
   # for i in range(depth):
   #     try:
   #         url = start_url + '&s=' + str(44*i)
   #         html = getHTMLText(url)
   #         print(html)
   #         parsePage(infolist,html)
   #     except:
   #         print("异常，继续")
   #         continue
   # printGoodsList(infolist)

main()

